var http = require('http')
var fs = require('fs')
var template = require('art-template')
var url = require('url')

var comments = [
    {name: '张三', message: '今天天气不错！', dateTime: '2017-09-11'},
    {name: '李四', message: '可靠的离开的，顶顶顶！', dateTime: '2017-10-13'},
    {name: '寂寞沙洲冷', message: '靠靠靠顶顶顶！', dateTime: '2017-01-12'},
    {name: 'bibi', message: '444444ggggggggg！', dateTime: '2017-10-16'},
    {name: '旧的boss', message: '双击666，老铁，没毛病！', dateTime: '2017-10-11'},
];
http.createServer(function (req, res) {
    var path_info = url.parse(req.url, true)
    var pathname = path_info.pathname
    if (pathname === '/'){
        fs.readFile('./view/index.html',function (err,data) {
            if (err){
                return res.end('404 not found')
            }
            var html = template.render(data.toString(), {
                comments:comments
            })
            // res.setHeader('Content-type', 'text/html;charset=utf-8')
            res.end(html)
        })
    }else if(pathname.indexOf('/public/') === 0){
        fs.readFile('.'+pathname,function (err,data) {
            if (err){
                return res.end('404 not found')
            }
            res.end(data)
        })
    }else if(pathname === '/post'){
        fs.readFile('./view/post.html',function (err,data) {
            if (err){
                return res.end('404 not found')
            }
            res.end(data)
        })
    }else if(pathname === '/pinglun'){
        var comment = path_info.query
        comment.dateTime = new Date().toLocaleString()
        comments.unshift(comment)
        res.statusCode = 302
        res.setHeader('Location','/')
        res.end()
    }else{
        fs.readFile('./view/404.html',function (err,data) {
            if (err){
                return res.end('404 not found')
            }
            res.end(data)
        })
    }
}).listen(3000, function () {
    console.log('server is running')
})